package common.impl;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.taobao.api.internal.util.StringUtils;
import common.interf.IBarCode;

/**
 * 二维码条形码功能类
 * 
 * @author yanglei
 * @since 2012-07-25
 */
public class BarCodeImpl implements IBarCode {
	/**
	 * 把url转换成二维码并保存
	 * 
	 * @param url
	 *            待转换的url
	 * @param savePath
	 *            存储路径
	 * @param fname
	 *            需要保存的文件名，为null则将字符串做MD5编码
	 * @return 保存后的文件名
	 */
	public String toQrCode(String url, String savePath, String fname) {
		try {
			BitMatrix matrix = new MultiFormatWriter().encode(url,
					BarcodeFormat.QR_CODE, 200, 200);
			int[] rec = matrix.getEnclosingRectangle();  
			int resWidth = rec[2] + 1;  
			int resHeight = rec[3] + 1;  
			BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
			resMatrix.clear();  
			for (int i = 0; i < resWidth; i++) {  
			    for (int j = 0; j < resHeight; j++) {  
			        if (matrix.get(i + rec[0], j + rec[1])) { 
			             resMatrix.set(i, j); 
			        } 
			    }  
			}  
			if (null == fname || StringUtils.isEmpty(fname))
				fname = MD5Transform.EncoderByMd5(url, "utf-8") + ".jpg";
			File savePathDirc = new File(savePath);
			if (!savePathDirc.exists()) {
				savePathDirc.mkdir();
			}
			File file = new File(savePath + "/" + fname);

			if (file.exists()) {
				fname = UUID.randomUUID() + ".jpg";
				file = new File(savePath + "/" + fname);
			}
			MatrixToImageWriter.writeToFile(resMatrix, "jpg", file);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
		}

		return fname;
	}

	/**
	 * 把url转换成二维码并保存
	 * 
	 * 自定义名字
	 * @param url
	 *            待转换的url
	 * @param savePath
	 *            存储路径
	 * @param fname
	 *            需要保存的文件名，为null则将字符串做MD5编码
	 * @return 保存后的文件名
	 */
	public String toQrCode_custom_name(String url, String savePath, String fname) {
		try {
			BitMatrix matrix = new MultiFormatWriter().encode(url,
					BarcodeFormat.QR_CODE, 200, 200);
			int[] rec = matrix.getEnclosingRectangle();  
			int resWidth = rec[2] + 1;  
			int resHeight = rec[3] + 1;  
			BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
			resMatrix.clear();  
			for (int i = 0; i < resWidth; i++) {  
			    for (int j = 0; j < resHeight; j++) {  
			        if (matrix.get(i + rec[0], j + rec[1])) { 
			             resMatrix.set(i, j); 
			        } 
			    }  
			}  
			//if (null == fname || StringUtils.isEmpty(fname))
				//fname = MD5Transform.EncoderByMd5(url, "utf-8") + ".jpg";
			File savePathDirc = new File(savePath);
			if (!savePathDirc.exists()) {
				savePathDirc.mkdir();
			}
			File file = new File(savePath + "/" + fname + ".jpg");

			//if (file.exists()) {
			//	fname = UUID.randomUUID() + ".jpg";
			//	file = new File(savePath + "/" + fname);
			//}
			MatrixToImageWriter.writeToFile(resMatrix, "jpg", file);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
		}

		return fname + ".jpg";
	}
	
	/**
	 * 把url转换成二维码并保存
	 * 
	 * @param url
	 *            待转换的url
	 * @param savePath
	 *            存储路径
	 * @param fname
	 *            需要保存的文件名，为null则将字符串做MD5编码
	 * @return 保存后的文件名
	 * @param width
	 *            生成二维码的宽
	 * @param height
	 *            生成二维码的高
	 * @return
	 */
	public String toQrOwnwhCode(String url, String savePath, String fname,
			Integer width, Integer height) {
		try {
			if (width == 0 || null == width) {
				width = 200;
			}
			if (height == 0 || null == height) {
				height = 200;
			}
			BitMatrix matrix = new MultiFormatWriter().encode(url,
					BarcodeFormat.QR_CODE, width, height);
			if (null == fname || !StringUtils.isEmpty(fname))
				fname = MD5Transform.EncoderByMd5(url, "utf-8") + ".jpg";

			// 路径，判断路径是否存在，不存在则新建
			File pathFile = new File(savePath);
			if (!pathFile.exists())
				pathFile.mkdirs();
			// 判断文件是否已存在，存在则修改文件名
			File file;
			while (true) {
				file = new File(savePath + "/" + fname);
				if (!file.exists())
					break;
				fname += "0";
			}
			MatrixToImageWriter.writeToFile(matrix, "jpg", file);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
		}

		return fname;
	}

	/**
	 * 把url转换成条码并保存
	 * 
	 * @param str
	 *            待转换的str
	 * @param savePath
	 *            存储路径
	 * @param fname
	 *            需要保存的文件名，为null则将字符串做MD5编码
	 * @return 保存后的文件名
	 */
	public String toBarCode(String str, String savePath, String fname) {
		try {
			BitMatrix matrix = new MultiFormatWriter().encode(str,
					BarcodeFormat.CODE_128, 300, 50);
			if (null == fname || !StringUtils.isEmpty(fname))
				fname = MD5Transform.EncoderByMd5(str, "utf-8") + ".jpg";
			File file = new File(savePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			file = new File(savePath + "/" + fname);
			MatrixToImageWriter.writeToFile(matrix, "jpg", file);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
		}
		return fname;
	}

}
